# Create your views here.
from django.http import HttpResponse
import json
from django.shortcuts import render
import csv
from django.conf import settings
from django.http import JsonResponse


def index(request):
    return render(request, 'index.html', context={})


def bar_data(request):           # 使用Django提供的settings.BASE_DIR作为绝对路径来读取本地文件
    with open(f'{settings.BASE_DIR}/static/data/sales_month.csv', 'r', encoding='utf-8') as file:
        reader = csv.DictReader(file)
        month = []
        sales = []
        profit = []
        for row in reader:
            month.append(row['month'])
            sales.append(float(row['sales']))
            profit.append(float(row['profit']))
    data = {'month': month, 'sales': sales, 'profit': profit}
    return JsonResponse(data, json_dumps_params={'indent': 4})


def map_data(request):
    with open(f'{settings.BASE_DIR}/static/data/sales_province.csv', 'r', newline='', encoding='gbk') as file:
        reader = csv.DictReader(file)
        province = []
        for row in reader:
            try:
                # 将sales字段转为 float 类型
                row['sales'] = float(row['sales'].strip())
                # 将 profit 字段转为 float 类型
                row['profit'] = float(row['profit'].strip())
            except ValueError:
                pass  # 转换失败，忽略该字段
            province.append(row)
    data = {'province': province}
    return JsonResponse(data, json_dumps_params={'indent': 4})


def sun_data(request):
    with open(f'{settings.BASE_DIR}/static/data/sales_product.json', 'r', encoding='utf-8') as f:
        # 读取JSON数据
        data = json.load(f)
        detail = {'detail': data}
        return JsonResponse(detail, json_dumps_params={'indent': 4})


def line_data(request):           # 使用Django提供的settings.BASE_DIR作为绝对路径来读取本地文件
    with open(f'{settings.BASE_DIR}/static/data/sales_region.csv', 'r', encoding='utf-8') as file:
        reader = csv.DictReader(file)
        region = []
        sales = []
        profit = []
        for row in reader:
            region.append(row['region'])
            sales.append(float(row['sales']))
            profit.append(float(row['profit']))
    data = {'region': region, 'sales': sales, 'profit': profit}
    return JsonResponse(data, json_dumps_params={'indent': 4})


def ld_data(request):           # 使用Django提供的settings.BASE_DIR作为绝对路径来读取本地文件
    with open(f'{settings.BASE_DIR}/static/data/sales_manager.csv', 'r', encoding='utf-8') as file:
        reader = csv.DictReader(file)
        sales_manager=[]
        sales = []
        profit = []
        for row in reader:
            sales_manager.append(row['sales_manager'].strip())
            sales.append(float(row['sales']))
            profit.append(float(row['profit'])*5)
        sales_manager_dict = [{'name': value,'max':800000} for value in sales_manager]
    data = {'sales_manager': sales_manager_dict, 'sales': sales, 'profit': profit}
    return JsonResponse(data, json_dumps_params={'indent': 4})